const express = require('express');
const {port} = require('./config.js');
const fs = require('fs');
const path = require('path');
const cron = require('node-cron');
const https = require('https');

const app = express();

console.log('NODE_ENV', process.env.NODE_ENV)

if(process.env.NODE_ENV === 'https') {
    const key = fs.readFileSync(path.resolve(__dirname, "./keys/localhost_10000_key.txt"),"utf-8"),
          cert = fs.readFileSync(path.resolve(__dirname, "./keys/localhost_10000_ssl.crt"),"utf-8");
    const options = { key, cert }
    https.createServer(options, app).listen(443)
}

// 每天23点59分删除临时文件
cron.schedule("59 23 * * *", function() {
    console.log("---------------------");
    console.log("Cron Job Start");
    const files = fs.readdirSync(path.resolve(__dirname, '../db/__temp__'));
    if(files.length > 0) {
        files.forEach(file => fs.unlinkSync(path.resolve(__dirname, `../db/__temp__/${file}`)));
    }
    console.log("Cron Job Done");
    console.log("---------------------");
});

app.use(express.static('public'));

app.use('/temp',express.static('db/__temp__'));

app.listen(port, () => {
    console.log(`BFFNODE-FE RUNNING`)
});

module.exports = app;